var ResourcesManager = function () {
	
	var resourceDto = {id:null, name:"",i18nKey:"",fId:"", url:"", rank:"", hasChild:"", type:"",isMenu:"",permissions:"",sortNum:""};
	
		
	var fnEditCallback= function(data){//Form表单提交信息
		$("#saveBtn").button("reset");
		$('#editDlg').modal('hide');
		if(data.type=='success') {
			BootstrapDialog.show({
	            title: messages.public_cue_message,
	            message: messages.public_cue_saveOk,
	            buttons: [{
	                label: messages.public_cue_sure,
	                cssClass: 'btn btn-sm btn-primary',
	                action: function(dialog) {
	                	UITree.refresh("tree_2");
	                	ResourcesManager.reSearch();
	                    dialog.close();
	                }
	            }]
	        });
		} else {
			BootstrapDialog.show({
	            title: messages.public_cue_error,
	            type: BootstrapDialog.TYPE_WARNING,
	            message: data.message,
	            buttons: [{
	                label: messages.public_cue_sure,
	                cssClass: 'btn btn-sm btn-primary',
	                action: function(dialog) {
	                    dialog.close();
	                }
	            }]
	        });
			
		}
	};
	var fnRemoveCallback= function(data){//Form表单提交信息
		if(data.type=='success') {
			BootstrapDialog.show({
	            title: messages.public_cue_message,
	            message: messages.public_cue_delSuccess,
	            buttons: [{
	                label: messages.public_cue_sure,
	                cssClass: 'btn btn-sm btn-primary',
	                action: function(dialog) {
	                	UITree.refresh("tree_2");
	                	ResourcesManager.reSearch();
	                    dialog.close();
	                }
	            }]
	        });
		} else {
			BootstrapDialog.show({
				type: BootstrapDialog.TYPE_WARNING,
	            title: messages.public_cue_error,
	            message: data.message,
	            buttons: [{
	                label: messages.public_cue_sure,
	                cssClass: 'btn btn-sm btn-primary',
	                action: function(dialog) {
	                    dialog.close();
	                }
	            }]
	        });
			
		}
	};
    return {
    	datatable:"",
        init: function () {
        	this.initTree();
        	this.search();
        	this.setListener();
        	this.formSubmit();
        },
        initTree:function(){
        	var doClick = function() {
    			$.ajax({
                    "type": "GET",
                    "cache": false,
                    "async " : false,
                    "url": ctx+"/resource/get/"+UITree.selectedId+"?now=" + new Date().getTime(), 
                    "success": function(data){
           				$("#treeType").val(data.type);
                    }
                });
    			
    			ResourcesManager.reSearch();
    	   	};
    		UITree.initTree({
    		   	"url" 		: ctx+"/resource/getTreeResources?pflag=true&now="+new Date().getTime(),
    		   	"id"	 	: "tree_2",
    		   	"checkbox"	:false,
    		   	"click"		: doClick,
    		   	"disable"	:false
    	   	});
        },
        search:function(){
        	if (!jQuery().dataTable) {
                return;
            }
            var resListTable  = $("#resListTable").dataTable({
                "sAjaxSource": ctx+"/resource/search?now="+new Date().getTime(), 
                /*使用post方式*/
        		"fnServerData": function ( sSource, aoData, fnCallback ) {
                	
        			var postData = {page:1,start:0,rows:10,params:{}};
        			//参数
        			postData.params.parentId = UITree.selectedId == "" ? 0 : (UITree.selectedId).toString();
        			for(var i=0,size=aoData.length;i<size;i++){
        				if(aoData[i].name=='iDisplayLength'){
        					postData.rows = aoData[i].value;
        				}else if(aoData[i].name=='iDisplayStart'){
        					postData.start = aoData[i].value;
        				}else if(aoData[i].name=='sEcho'){
        					postData.page = aoData[i].value;
        				}
        			}
                    $.ajax({
                        "dataType": 'json',
                        "cache": false,
                        "type": "POST",
                        "url": sSource,
                        "data": postData,
                        "success": function(data, textStatus, jqXHR){
							fnCallback(data.data, textStatus, jqXHR);
						}
                    });
                },
                "aoColumnDefs": [  
                    {  
                      "data": "name",
  		              "aTargets": [ 0 ],
                      'bSortable': true
                    },{  
                       "data": "url",
    		           "aTargets": [ 1 ]
                    },{  
                        "data": "permissions",
     		           "aTargets": [ 2 ]
                     },{  
                    	"data": "sortNum",
     		        	"aTargets": [ 3 ]
                    },{
	                	"aTargets": [ 4 ],  
                		"mRender": function ( data, type, full ) { 
                			var btns =  '';
							btns +=  Permission.createPermElement('resource:list:modify','<button title="'+messages.public_button_edit+'" class="btn btn-sm-table btn-primary" name="edit" target_id="'+full.id+'">编辑</button>');
							btns += Permission.createPermElement('resource:list:del',' <button title="'+messages.public_button_del+'" href="javascript:;" class="btn btn-sm-table btn-danger" name="del" target_id="'+full.id+'">删除</button>');
							return btns;
                			
	                	}  
	                }  
                 ]
            });
            datatable = resListTable;
        },
        reSearch : function(){
        	datatable.fnDraw();
        },
        setListener:function(){
        	jQuery("#newMenuBtn").click(function(){
        		if($("#treeType").val()!=""){
        			BootstrapDialog.show({
        	            title: messages.public_cue_error,
        	            type: BootstrapDialog.TYPE_WARNING,
        	            message: "该层级不可添加目录！",
        	            buttons: [{
        	                label: messages.public_cue_sure,
        	                cssClass: 'btn btn-sm btn-primary',
        	                action: function(dialog) {
        	                    dialog.close();
        	                }
        	            }]
        	        });
        		}else{
        			resourceDto = {id:null, name:"",i18nKey:"",parentId:"0", url:"", seq:"", type:"0", isMenu:"1", hasChild:1,permissions:"",sortNum:""};//hasChild:"", 
            		$("div[name=editDlg] h4.modal-title").html("新增菜单");
            		ResourcesManager.removeClass();
            		ResourcesManager.fInit(resourceDto);
        		}
        	});
        	jQuery("#newBtn").unbind("click").click(function(){
        		if($("#treeType").val()==""){
        			BootstrapDialog.show({
        	            title: messages.public_cue_error,
        	            type: BootstrapDialog.TYPE_WARNING,
        	            message: "请先增加目录,再添加资源！",
        	            buttons: [{
        	                label: messages.public_cue_sure,
        	                cssClass: 'btn btn-sm btn-primary',
        	                action: function(dialog) {
        	                    dialog.close();
        	                }
        	            }]
        	        });
        		}else if($("#treeType").val()=="1"){
        			BootstrapDialog.show({
        	            title: messages.public_cue_error,
        	            type: BootstrapDialog.TYPE_WARNING,
        	            message: "该层为最低层级无法新增资源！",
        	            buttons: [{
        	                label: messages.public_cue_sure,
        	                cssClass: 'btn btn-sm btn-primary',
        	                action: function(dialog) {
        	                    dialog.close();
        	                }
        	            }]
        	        });
        		}else{
        			resourceDto = {id:null, name:"",i18nKey:"",parentId:"0", url:"", seq:"", hasChild:"", type:"1",isMenu:"",permissions:"",sortNum:""};
            		if(UITree.selectedId != null && (UITree.selectedId).toString() != ''){
            			resourceDto.parentId = (UITree.selectedId).toString();
            			resourceDto.type = "1";//级数
            			resourceDto.isMenu = "0";//是否是菜单 1是，0不是
            			resourceDto.hasChild = "0";//0表示无子菜单
            			$("div[name=editDlg] h4.modal-title").html("新增资源");
            			ResourcesManager.fInit(resourceDto);
            			ResourcesManager.removeClass();
                	} else {
            			ResourcesManager.showWarn();
                	}
        		}
        		return false;
        	});
        	
        	jQuery("#newButtonBtn").unbind("click").click(function(){
        		if($("#treeType").val()==""){
        			BootstrapDialog.show({
        	            title: messages.public_cue_error,
        	            type: BootstrapDialog.TYPE_WARNING,
        	            message: "请先增加目录,再添加资源！",
        	            buttons: [{
        	                label: messages.public_cue_sure,
        	                cssClass: 'btn btn-sm btn-primary',
        	                action: function(dialog) {
        	                    dialog.close();
        	                }
        	            }]
        	        });
        		}else{
        			resourceDto = {id:null, name:"",i18nKey:"",parentId:null, url:"", seq:"", hasChild:"", type:"2",isMenu:"",permissions:"",sortNum:""};
            		if(UITree.selectedId != null && (UITree.selectedId).toString() != ''){
            			resourceDto.parentId = (UITree.selectedId).toString();
            			resourceDto.isMenu = "0";//是否是菜单 1是，0不是
            			resourceDto.hasChild = "0";//0表示无子菜单
            			$("div[name=editDlg] h4.modal-title").html("新增按钮");
            			ResourcesManager.fInit(resourceDto);
            			ResourcesManager.removeClass();
                	} else {
            			ResourcesManager.showWarn();
                	}
        		}
        		return false;
        	});

        	$('#resListTable tbody').on('click', 'button[name="edit"]',function() {
				var id = $(this).attr("target_id");
				ResourcesManager.eInit(id);
			});
			$('#resListTable tbody').on('click', 'button[name="del"]',function() {
				var id = $(this).attr("target_id");
				ResourcesManager.remove(id);
			});
			
        },
        formSubmit:function(){
        	var form1 = $('#editForm');
            form1.validate({
                rules: {
                    name: {
                        minlength: 2,
                        maxlength:10,
                        required: true
                    },
                    url: {
                        required:true,
                        maxlength:50
                    },
                    permissions:{
                    	required: true
                    },
                    seq: {
                    	number: true,
                    	required: true,
                    	range:[1,100],
                    	digits : true
                    }
                },submitHandler: function (form) {//提交
                	$("#saveBtn").button("loading");
                	$.ajax({
                        "dataType": 'json',
                        "cache": false,
                        "type": "POST",
                        "url": ctx+"/resource/edit?now=" + new Date().getTime(), 
                        "data": $(form).serializeJson(),
                        "success":fnEditCallback 
                    });
                }
            });
        },
        fInit:function(dto){
        	$("#editForm").binddata(dto);
        	$("#editDlg").modal('show');
        },
        eInit:function(id){
        	$("div[name=editDlg] h4.modal-title").html(messages.public_button_edit);
    	    ResourcesManager.removeClass();
        	$.ajax({
                "type": "GET",
                "cache" : false,
                "url": ctx+"/resource/get/"+id+"?now=" + new Date().getTime(), 
                "success": function(data){
                	ResourcesManager.fInit(data.data);
                }
            });
        },
        showWarn:function(){
    		BootstrapDialog.show({
    			type: BootstrapDialog.TYPE_WARNING,
    			title: messages.public_cue_warning,
    			message: '请先选择资源所属的菜单！',
    			buttons: [{
    				label: messages.public_cue_close,
    				cssClass: 'btn btn-sm btn-default',
    				action: function(dialogItself){
    					dialogItself.close();
    				}
    			}]
    		});
        },
        removeClass:function(){
        	//去除Form表单的验证样式
        	$('.form-group','#editForm').removeClass('has-success')
            .removeClass('has-error');
    		 $('span').remove('.help-block');
        },
        remove:function(id){
        	BootstrapDialog.show({
                type: BootstrapDialog.TYPE_WARNING,
                title: messages.public_cue_warning,
                message: messages.public_cue_delSure,
                buttons: [{
                    label: messages.public_cue_close,
                    cssClass: 'btn btn-sm btn-default',
                    action: function(dialogItself){
                        dialogItself.close();
                    }
                },{
                    label: messages.public_cue_sure,
                    cssClass: 'btn btn-sm btn-primary',
                    action:function(dialogItself){
                    	$.ajax({
                            "type": "GET",
                            "cache": false,
                            "url": ctx+"/resource/delete/"+id+"?now="+new Date().getTime(), 
                            "success": fnRemoveCallback
                        });
                    	dialogItself.close();
                    }
                }]
            });  
        }
    };

}();